package org.lewis.woman.service;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbutils.DbUtils;
import org.lewis.common.domain.VCode;
import org.lewis.common.jdbc.QueryHelper;
import org.lewis.common.service.VCodeService;

import com.tocersoft.framework.core.annotations.Component;

@Component
public class VCodeServiceImpl implements VCodeService {

	public long addVCode(VCode code) {
		String sql="insert into ts_vcode (code,uid,type,createTime) values (?,?,?,?)";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = QueryHelper.getConnection().prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
			ps.setObject(1, code.getCode());
			ps.setObject(2, code.getUid());
			ps.setObject(3, code.getType());
			ps.setObject(4, code.getCreateTime());
			ps.executeUpdate();
			rs = ps.getGeneratedKeys();
			return rs.next() ? rs.getLong(1) : -1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(rs);
			DbUtils.closeQuietly(ps);
		}
		return 0;
	}

	public VCode getByCode(String code) {
		String sql="select id,code,uid,type,createTime from ts_vcode where code=?";
		return QueryHelper.get(VCode.class, sql, code);
	}

	public long removeCode(Long id) {
		String sql="delete from ts_vcode where id=?";
		return QueryHelper.update(sql, id);
	}

	public VCode getByCode(Long uid, String type) {
		String sql="select id,code,uid,type,createTime from ts_vcode where uid=? and type=?";
		return QueryHelper.get(VCode.class, sql, uid,type);
	}

}
